package graphics.raytracing;


import static util.MatrixOperationsF.ar;
import static util.MatrixOperationsF.print;

import java.io.FileNotFoundException;

import graphics.datastructures.BoundingBox;
import graphics.datastructures.SimpleMesh;
import graphics.datastructures.Triangle;
import graphics.datastructures.hierarchalbb.HierarchalBoundingBox;
import graphics.raytracing.shaders.PhongShader;
import graphics.raytracing.shaders.RandomColorShader;
import drawing.DrawingEngine;

public class RayTracerCore {
	int xmax = 500;
	int ymax = 500;
	private DrawingEngine engine;
	private SimpleWindowWithCallback window;
	private DirectionalLigtSource source;
	private CameraPosition pos;
	private SimpleMesh<Triangle> model;
	private HierarchalBoundingBox<Triangle> box;
	public RayTracerCore(String[] args) throws FileNotFoundException
	{
		engine = new DrawingEngine(xmax, ymax);
		engine.go();
		pos = new CameraPosition(ar(0, 1.5f, -40), ar(1, 1, 1),ar(0,0,0));
		source = new DirectionalLigtSource(ar(-1, -1,-1));
		window = new SimpleWindowWithCallback(ar(-3, -3, -10), ar(10, 0,
				0), ar(0, 10, 0), xmax, ymax, source, engine, xmax * ymax / 10,
				pos);
		
		window.setShader(new RandomColorShader());
		//yryyrm,rydyppgb;rrd
		io.ModelReader reader = new io.SimpleReader(
				args[0]);
		System.out.println("started");
		 model = (SimpleMesh<Triangle>) reader.read();
		System.out.println("finished reading");
		System.out.println("start building hierarchy");
		 box = new HierarchalBoundingBox<Triangle>(
				model.getTracables(), new BoundingBox<Triangle>(model.getBB()[0],
						model.getBB()[1]));
		System.out.println("hierarchy build");
		System.out.println("model reading completed");
		
	}
	public void start() throws Exception {
		RayTracer tracer = new RayTracer(box, window, pos);
		while (true) {
			long time = System.currentTimeMillis();
			System.out.println("started rendering");
			engine.clear();
			engine.notifyChange();
			System.out.println(print(pos.getOrigin()));
			tracer.setCamera(pos);
			tracer.traceRays();
			engine.notifyChange();
			System.out.println("time rendering:"
					+ (System.currentTimeMillis() - time) / 1000 + " s");
			System.in.read();
			Thread.sleep(3000);
		}
	}

}